import React from 'react';
import { Select } from 'antd';
import ajax from '../../../utils/ajax';

const Option = Select.Option;
var _this;

//用户管理 分配角色
class DisRole extends React.Component {

  state = {
    roleAllChild: [], //现有的所有角色
    roleUserChild: [], //被选中的用户所拥有的角色
  }

  componentWillMount = () => {
    this.initRoleData(this.props);
  }

  componentWillReceiveProps = (nextProps) => {
    this.initRoleData(nextProps);
  }

  initRoleData = (prop) => {
    _this = this;
    if (prop.defaultValue!=undefined) {
      let temp=prop.defaultValue;
      for(let i=0;i<temp.length;i++){
        temp[i] = temp[i].toString(); 
      }
       _this.setState({ roleUserChild: temp });
    }
    else {
      let updateId = prop.updateId.join("");
      ajax.post({
        url: "/user/getAssignRole",
        params: { userId: updateId },
        success: function (res) {

          const allRoleData = res.data.roles;  //加载所有角色

          const allRole = allRoleData.map((node) => {
              return (<Option key={node.id} >{node.name}</Option>);
          });

          _this.setState({ roleAllChild: allRole });

          let userRoleData = res.data.userRoles;//当前用户拥有的角色

          let userRole = [];

          for (let i = 0; i < userRoleData.length; i++) {
            let userRoleItem = {};
            userRoleItem = userRoleData[i].role.id.toString();  //数组的项必须为字符串
            console.log(userRoleItem);
            userRole.push(userRoleItem);
          }

          _this.setState({ roleUserChild: userRole });
          _this.props.updateRole(userRole);

        }
      })
    }

  }

  handleDisRoleChange = (value) => {
    this.setState({ roleUserChild: value });
    this.props.updateRole(value);
  }

  render() {
    return (
      <div>
        <Select
          multiple
          style={{ width: '100%' }}
          placeholder="请选择要分配的角色"
          onChange={this.handleDisRoleChange}
          value={this.state.roleUserChild}
          >
          {this.state.roleAllChild}
        </Select>
      </div>
    );

  }

}

export default DisRole;
